﻿using System;
using System.Collections.Generic;
using BlogEngine.Core;
using NoRM;
using System.Linq;
using System.Linq.Expressions;

namespace BlogEngine.MongoDbProvider
{
    public class MongoDb
    {
        private readonly string _dbName;

        public MongoDb(string dbName)
        {
            _dbName = dbName;
        }

        public Mongo GetServer()
        {
            return new Mongo(_dbName);
        }

        public void Insert<TEntity>(TEntity entity) where TEntity : class, new()
        {
            GetServer().GetCollection<TEntity>().Insert(entity);
        }

        public IEnumerable<TEntity> Select<TEntity>(Expression<Func<TEntity, bool>> expression)
        {
            using (var server = GetServer())
            {
                return server.GetCollection<Post>()
                    .Find(expression);
            }
        }

        public TEntity SelectOne<TEntity>(Expression<Func<TEntity, bool>> expression) where TEntity : class, new()
        {
            using (var server = GetServer())
            {
                return server.GetCollection<TEntity>()
                    .FindOne(expression);
            }
        }

        public IQueryable<TEntity> GetQueryableFor<TEntity>() where TEntity : class, new()
        {
            return GetServer().GetCollection<TEntity>() as IQueryable<TEntity>;
        }

        public static string GetCollectionNameFor<TEntity>()
        {
            return typeof (TEntity).Name + "Docs";
        }

        public void Delete<TEntity>(TEntity entity) where TEntity : class, new()
        {
            using (var server = GetServer())
            {
                server.GetCollection<TEntity>().Delete(entity);
            }
        }
    }
}